<template>
	<scroll-view class="backview" bounces="false" :style="{ height: scrollHeight + 'px'}" scroll-y
			:scroll-with-animation='true'>
		<view class="top-menu">
		</view>
		<!-- 	<scroll-view class="words-scroll" :style="{ height: scrollHeight + 'px'}" scroll-y
			:scroll-with-animation='true'> -->
		<!-- 顶部菜单 -->
		<view class='match-header'>
			<wordClickGameNaviration ref='gameNavigation' :countDown="countDown" :countDownTime="countDownTime"
				@gameBack="handleGameBack" @gameNext="gameNextTap">
			</wordClickGameNaviration>
		</view>
		<!-- 题目内容 -->
		<view class='match-content'>
			<wordClickGameContentView ref='wordClickGameContentViewRef' :topic='topic'
				@startCountdown="handleStartCountDown" @confirmTopic='handleConfirmTopic'>
			</wordClickGameContentView>
		</view>
		<view class="keyboard-class">
			<customSoftKeyboard ref='keyboardRef' @input="inputChange">
			</customSoftKeyboard>
		</view>
		<!-- </scroll-view> -->
		<selectContentView v-if="showMask" :msg="ReportPromptMsg" confirmTitle="保留" cancelTitle="不保留"
			@confirm="backPlanTap" @cancel="removePlanData"></selectContentView>
		<popPromptBox v-if="showPromptbox" :msg="PromptMsg" @confirm="hidePromptbox"></popPromptBox>
	</scroll-view>
</template>

<script>
	import util from '../../utils/util';
	import wordClickGameNaviration from '../../components/planBeeCom/wordClickGameNaviration.vue'
	import wordClickGameContentView from '../../components/planBeeCom/wordClickGameContentView.vue'
	import customSoftKeyboard from '../../components/customSoftKeyboard.vue';
	export default {
		components: {
			customSoftKeyboard,
			wordClickGameContentView,
			wordClickGameNaviration
		},
		data() {
			return {
				backstage: false, // 是否进手机后台
				scrollHeight: 0,
				countDownTime: '',
				countDown: null,
				Totalscore: '',
				FrenchDict: {
					à: 'a',
					â: 'a',
					è: 'e',
					é: 'e',
					ê: 'e',
					î: 'i',
					ï: 'i',
					ô: 'o',
					ö: 'o',
					ù: 'u',
					û: 'u',
					ü: 'u',
					ç: 'c'
				},
				showPromptbox: false,
				currentQuestionType: -1,
				allowInput: false,
				showMask: false,
				countDown_num: 5,
				interval: '',
				topic: {},
				useranswers: {},
				quizId: '',
				isAllowNext: true, //是否允许进入下一题（为了避免用户答错在提示期间，倒计时结束进入下一题）
				ReportPromptMsg: '退出当前打卡是否保留当前打卡记录？'
			}
		},
		onBackPress(options) {
			// 点击虚拟键或者侧滑的时候触发（不允许返回）
			if (options.from === 'backbutton') {
				return true
			}
			// 否则则允许返回
			return false;
		},
		onReady() {
			const that = this;
			uni.createSelectorQuery().select('.top-menu').boundingClientRect(rect => {
				console.log('rect', rect);
				that.scrollHeight = uni.getSystemInfoSync().windowHeight - rect.bottom;
			}).exec();
		},
		methods: {
			// 答题的倒计时
			handleStartCountDown: function() {
				var countDown = this.calCountDownForType();
				this.beginDownNum(countDown);
			},
			beginDownNum(countDown) {
				var that = this;
				clearInterval(that.interval) //停止之前的定时器
				var interval = setInterval(function() {
					countDown--;
					if (countDown > 0) {
						var countDown_time = util.sec_to_time(countDown.toString()).substr(3, 5);
						that.countDown = countDown;
						that.countDownTime = countDown_time;
					}
					if (countDown <= 0) {
						if (that.isAllowNext == true) {
							clearInterval(interval);
							this.interval = null;
							that.$refs.gameNavigation.hidePromptbox();
							that.checkAnswerAndQuestion('timeout');
						}
					}
				}, 1000)
				this.interval = interval;
			},
			// 不保留打卡数据
			removePlanData: function(e) {
				//删除缓存
				var beePlanKey = 'beePlanDate' + this.planType + this.beePlanLogId + this.dayId;
				uni.removeStorage({
					key: beePlanKey,
				})
				this.backPlanTap();
			},
			// 隐藏弹窗/退出
			backPlanTap: function() {
				this.showMask = false;
				this.endMatch();
			},
			//考试中返回
			handleGameBack: function() {
				this.showMask = true;
			},
			handleGameNext: function() {
				this.isAllowNext = true;
				var that = this;
				// 需要提前取消正在下载的题，取消下载任务操作也是异步的
				// 如果下一题的下载任务开始了，可能导致无法取消当前题目的下载
				this.$refs.wordClickGameContentViewRef.handlePlayRadioStop();
				// 清空输入
				this.$refs.keyboardRef.emptyInput();
				// 获取下一题
				// 这里需要延迟执行，给取消下载任务的时间
				setTimeout(function() {
					that.answerAndNext();
				}, 500);
			},
			//每道题的倒计时时间s
			calCountDownForType: function() {
				return 60;
			},
			/**
			 * 配合键盘输入事件：input，获取输入内容到虚拟输入框中
			 */
			inputChange: function(e) {
				console.log('e', e);
				var topic = this.topic;
				topic.question = e.keyboardValue;
				this.topic = topic;
			},
			gameNextTap: function() {
				this.checkAnswerAndQuestion('pass');
			},
			// 点击确认按钮或到时间自动提交单个题目
			checkAnswerAndQuestion: function(way) {
				var useranswer = {};
				var answerarray = [];
				useranswer.wordId = this.topic.id;
				useranswer.spell = this.topic.spell;
				if (this.topic.errorWordId) {
					useranswer.id = this.topic.errorWordId;
				}
				useranswer.isErrorWord = this.topic.isErrorWord;
				if (way == 'normal') {
					var spellStr = this.excludeSpecial(this.topic.spell);
					console.log('spellStr', spellStr);
					// 判断是否正确
					if (spellStr.indexOf('/') >= 0) {
						var newSpellArray = spellStr.split("/");
						for (let index = 0; index < newSpellArray.length; index++) {
							const element = newSpellArray[index];
							if (this.topic.question.toLowerCase().replace(/\s*/g, "") == element.toLowerCase()
								.replace(/\s*/g, "")) {
								useranswer.isCorrect = 0;
								break;
							} else {
								useranswer.isCorrect = 1;
							}
						}
					} else {
						if (this.topic.question.toLowerCase().replace(/\s*/g, "") == spellStr.toLowerCase()
							.replace(/\s*/g, "")) {
							useranswer.isCorrect = 0;
						} else {
							useranswer.isCorrect = 1;
						}
					}
					useranswer.userSpell = this.topic.question;
				} else if (way == 'pass') {
					useranswer.userSpell = '';
					useranswer.isCorrect = 1;
				} else {
					useranswer.userSpell = '';
					useranswer.isCorrect = 1;
				}
				answerarray.push(useranswer);
				this.allquestionAnswer = [...this.allquestionAnswer, ...answerarray];
				this.saveBeePlanData.beePlanIndex = this.topic.num;
				this.saveBeePlanData.answerarray = this.allquestionAnswer;
				uni.setStorageSync(this.saveKeyStr, JSON.stringify(this.saveBeePlanData));
				if ((way == 'normal' && useranswer.isCorrect == 1) || way == 'timeout') {
					clearInterval(this.interval) //停止之前的定时器
					this.isAllowNext = false;
					this.PromptMsg = '正确拼写: ' + this.topic.spell;
					this.showPromptbox = true;
					this.$refs.wordClickGameContentViewRef.handlePlayRadioStop();
				} else {
					this.handleGameNext();
				}
			},
			// 法语映射为普通字母
			excludeSpecial: function(s) {
				var letter = s;
				var engStr = 'àâèéêîïôöùûüç';
				var frenchArray = [];
				// var frenchStr = "";
				for (let index = 0; index < s.length; index++) {
					const element = s.charAt(index);
					if (element == 'à' || element == 'â') {
						letter = letter.replace(element, 'a');
					}
					if (element == 'è' || element == 'é' || element == 'ê') {
						letter = letter.replace(element, 'e');
					}
					if (element == 'î' || element == 'ï') {
						letter = letter.replace(element, 'i');
					}
					if (element == 'ô' || element == 'ö') {
						letter = letter.replace(element, 'o');
					}
					if (element == 'ù' || element == 'û' || element == 'ü') {
						letter = letter.replace(element, 'u');
					}
					if (element == 'ç') {
						letter = letter.replace(element, 'c');
					}
				}
				return letter;
			},
			// 点击确定按钮提交
			handleConfirmTopic: function() {
				var that = this;
				// 点击确认，判断是否正确,获取下一题
				if (this.topic.question == '') {
					uni.showToast({
						title: '拼写单词不能为空',
						icon: 'none',
						duration: 1000,
					})
					return;
				}
				this.checkAnswerAndQuestion('normal');
			},
			answerAndNext: function() {
				// 销毁上一题的音频
				this.$refs.wordClickGameContentViewRef.handlePlayRadioStop();
				this.questionsIndex = this.questionsIndex += 1;
				if (this.questionsIndex < this.wordLibrary.length) {
					clearInterval(this.interval);
					this.interval = null;
					var countDown = this.calCountDownForType();
					var countDown_time = util.sec_to_time(countDown.toString()).substr(3, 5);
					this.countDown = countDown;
					this.countDownTime = countDown_time;
					this.uploadView((this.topic.num + 1));
				} else {
					if (this.planType == 'review') {
						this.uploadNewWordSheetdata();
					} else {
						this.uploadfinishedSheetdata();
					}
				}
			},
			// 提交生词记录
			uploadNewWordSheetdata: function() {
				clearInterval(this.interval);
				uni.showLoading({
					title:'保存中...'
				})
				let formData = {};
				var errorWordIds = [];
				var punchClockWordIds = [];
				for (let index = 0; index < this.allquestionAnswer.length; index++) {
					const element = this.allquestionAnswer[index];
					if (element.isCorrect == 0) {
						punchClockWordIds.push(element.wordId)
					} else {
						errorWordIds.push(element.wordId)
					}
				}
				formData.errorWordIds = errorWordIds;
				formData.successWordIds = punchClockWordIds;
				this.$http.reviewErrWord(formData).then(res => {
					console.log('reviewErrWord', res);
					if (res.code == 200) {
						var savaData = {
							resultData: res.data,
							dayId: this.dayId,
							answerData: this.allquestionAnswer,
							beePlanLogId: this.beePlanLogId,
							planType: this.planType
						}
						uni.setStorageSync("endResultData", savaData);
						uni.redirectTo({
							url: '/pages/planBee/wordClockAnwsereEndResult',
						})
					} else {
						var that = this;
						uni.showModal({
							title: '提示',
							content: '复习结果上传过程中' + res.msg + '，是否重新上传成绩？',
							cancelText: '取消上传',
							confirmText: '重新上传',
							success: function(res) {
								if (res.confirm) {
									that.uploadNewWordSheetdata();
								} else {
									uni.navigateBack();
								}
							},
						})
					}
				})
			},
			//完成考试或异常退出时上传结果
			uploadfinishedSheetdata: function() {
				clearInterval(this.interval);
				let formData = {};
				formData.record = JSON.stringify(this.allquestionAnswer);
				formData.id = this.dayId;
				var errorWordIds = [];
				var punchClockWordIds = [];
				for (let index = 0; index < this.allquestionAnswer.length; index++) {
					const element = this.allquestionAnswer[index];
					if (element.isCorrect == 0) {
						punchClockWordIds.push(element.wordId)
					} else {
						errorWordIds.push(element.wordId)
					}
				}
				formData.errorWordIds = errorWordIds;
				formData.punchClockWordIds = punchClockWordIds;
				formData.replacement = this.wordReview == 'fillCard' ? true : false;
				console.log('formData___', formData);
				this.$http.punchClockSubmit(formData).then(res => {
					if (res.code == 200) {
						this.getResultData();
					} else {
						var that = this;
						uni.showModal({
							title: '提示',
							content: '打卡结果上传过程中' + res.msg + '，是否重新上传成绩？',
							cancelText: '取消上传',
							confirmText: '重新上传',
							success: function(res) {
								if (res.confirm) {
									that.uploadfinishedSheetdata();
								} else {
									uni.navigateBack();
								}
							},
						})
					}
				})
			},
			getResultData: function() {
				this.$http.getPnchClockLog({
					id: this.dayId
				}).then(res => {
					if (res.code == 200) {
						var savaData = {
							resultData: res.data,
							dayId: this.dayId,
							answerData: this.allquestionAnswer,
							beePlanLogId: this.beePlanLogId,
							planType: this.planType
						}
						uni.setStorageSync("endResultData", savaData);
						uni.redirectTo({
							url: '/pages/planBee/wordClockAnwsereEndResult',
						})
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000,
						})
					}
				})
			},
			uploadView: function(num) {
				var newPreliminaryData = this.wordLibrary[num - 1];
				this.showMask = false;
				this.showCountDown = false;
				this.currentQuestionType = 2;
				// 初始化题型数据
				var topic = newPreliminaryData;
				topic.question = '';
				topic.num = num;
				topic.curIndex = num - 1;
				this.topic = topic;
				this.$refs.keyboardRef.emptyInput();
				this.$nextTick(() => {
					if (num > 1) {
						this.$refs.wordClickGameContentViewRef.startTimeDown();
					}
					this.$refs.wordClickGameContentViewRef.audioPronounciation();
				});
			},
			endMatch: function() {
				// 销毁上一题的音频
				this.$refs.wordClickGameContentViewRef.handlePlayRadioStop();
				uni.navigateBack();
			},
			//隐藏提示
			hidePromptbox: function() {
				this.showPromptbox = false;
				this.handleGameNext();
			}
		},
		onLoad(options) {
			var wordListJson = JSON.parse(this.$globalData.wordListJson);
			var beePlanIndex = options.beePlanIndex ? Number(options.beePlanIndex) : 1;
			if (beePlanIndex > wordListJson.length) {
				beePlanIndex -= 1;
			}
			var beePlanKey = 'beePlanDate' + options.planType + options.beePlanLogId + options.dayId;
			this.dayId = options.dayId;
			this.wordReview = options.wordReview;
			this.allquestionAnswer = options.answerarray ? JSON.parse(options.answerarray) : [];
			this.planType = options.planType;
			this.questionsIndex = beePlanIndex - 1;
			this.beePlanLogId = options.beePlanLogId;
			this.wordLibrary = wordListJson;
			const saveBeePlanData = {
				'planWordListData': wordListJson,
				'beePlanLogId': options.beePlanLogId,
				'beePlanIndex': beePlanIndex,
				'answerarray': options.answerarray ? JSON.parse(options.answerarray) : [],
			};
			console.log('saveBeePlanData', saveBeePlanData);
			this.saveBeePlanData = saveBeePlanData;
			this.saveKeyStr = beePlanKey;
		},

		mounted() {
			this.uploadView(this.saveBeePlanData.beePlanIndex);
		},
		onHide() {
			if (this.interval) {
				this.backstage = true;
				clearInterval(this.interval);
				this.interval = null;
			}
		},
		onShow() {
			if (!this.interval && this.backstage == true && this.countDown > 0) {
				this.backstage = false;
				this.beginDownNum(this.countDown)
			}
		},
		onUnload() {
			// 销毁音频
			if (this.$refs.wordClickGameContentViewRef) {
				this.$refs.wordClickGameContentViewRef.handlePlayRadioStop();
			}
			if (this.interval) {
				clearInterval(this.interval);
				this.interval = null;
			}
		}
	}
</script>

<style lang="less">
	.backview {
		width: 100%;
		height: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		top: 0;
		right: 0;
		background: var(--contentBackColor);
	}

	.match-header {
		text-align: center;
		width: 100%;
		z-index: 1000;
	}

	.top-menu {
		width: 100%;
		height: 1px;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-around;
	}

	.match-content {
		width: 100%;
		margin-top: 20px;
	}

	.match-game-footer {
		margin-top: 330px;
		margin-bottom: 15px;
	}

	.keyboard-class {
		width: 100%;
		margin-top: 20px;
	}
</style>